<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      :show-checkbox="true"
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <!-- 添加按钮 -->
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Add
          </el-button>
          <!-- 修改按钮 -->
          <el-button type="text" size="mini" @click="() => edit(data)">
            Update
          </el-button>
          <!-- 删除按钮 -->
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="表单名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.product_count"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumbitBool">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>



<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},

  data() {
    return {
      pCid: [],
      draggable: false,
      updateNodes: [],
      dialogType: [],
      title: "",
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: "",
        product_count: "",
      },
      dialogVisible: false,
      expandedKey: [],
      menus: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  methods: {
    //自定义获取三级菜单
    getDataMenu() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("成功获取！！", data.page);
        this.menus = data.page;
      });
    },
    //对话框判断是修改还是添加的方法
    sumbitBool() {
      if (this.dialogType == "update") {
        this.updateCategory();
      }
      if (this.dialogType == "add") {
        this.addCategory();
      }
    },
    //修改第三方数据具体实现方法
    updateCategory() {
      var { name, icon, product_count, catId } = this.category;
      var data = {
        name: name,
        productCount: product_count,
        catId: catId,
        icon: icon,
      };
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(data, false),
      }).then(({ data }) => {
        this.$notify({
          title: "成功",
          message: "修改菜单成功！！！",
          type: "success",
        });
        this.dialogVisible = false;
        this.getDataMenu();
        console.info(data);
        this.expandedKey = [this.category.parentCid];
      });
    },
    //修改第三方数据方法
    edit(data) {
      console.info("修改中----", data);
      this.dialogType = "update";
      this.title = "修改分类";
      this.dialogVisible = true;
      // 发送http请求获取最新数据信息
      this.$http({
        url: this.$http.adornUrl("/product/category/info/" + data.catId),
        method: "get",
        params: this.$http.adornParams({}),
      }).then(({ data }) => {
        console.info("获取----", data);
        this.category.name = data.category.name;
        this.category.catId = data.category.catId;
        this.category.icon = data.category.icon;
        this.category.product_count = data.category.productCount;
        this.category.parentCid = data.category.parentCid;
      });
    },
    //添加第三方数据方法
    addCategory() {
      this.title = "添加分类";
      console.info("提交的三级分类数据", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.$notify({
          title: "成功",
          message: "保存成功！！！",
          type: "success",
        });
        this.dialogVisible = false;
        this.getDataMenu();
        this.expandedKey = [this.category.parentCid];
      });
    },
    //添加菜单方法
    append(data) {
      this.category.name = "";
      this.title = "添加分类";
      this.dialogType = "add";
      this.category.product_count = "";
      console.log(data);
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
    },
    //删除菜单方法
    remove(node, data) {
      var ids = [data.catId];
      this.$confirm("是否删除【" + data.name + "】菜单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {});
          this.$notify({
            title: "成功",
            message: "这是一条成功的提示消息",
            type: "success",
          });
          this.getDataMenu();
          this.expandedKey = [node.parent.data.catId];
        })
        .catch(() => {});
    },
    //拖拽方法
    allowDrop(draggingNode, dropNode, type) {
      //被拖动的节点的深度加加目标节点的节点层级之和小于最大层级数
      console.log("allowDrop:", draggingNode, dropNode, type);
      var number = this.countNodeLevel(draggingNode);
      console.log("number:",number,"dropNode.level:",dropNode.level);
      if (type == "inner") {
        return number + dropNode.level <= 3;
      } else {
        return number + dropNode.parent.level <= 3;
      }
    },
    //计算最大子节点 找出最大深度
    countNodeLevel(node) {
      //找到所有子节点，求出最大深度
      var maxLevel = 1;
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > maxLevel) {
            maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
        //计算深度
        if(maxLevel == 2){
          maxLevel = maxLevel -node.level + 2;
        }else{
           maxLevel = maxLevel - node.level + 1;
        }
      }
      return maxLevel;
    },
    //节点拖拽成功的监听
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("tree drop: ", draggingNode, dropNode, dropType);
      var siblings = null;
      var pCid = 0;
      //更新父节点
      if (dropType == "inner") {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      } else {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      }
      this.pCid.push(pCid);
      //更新当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //如果遍历的是拖动的节点
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            //如果拖动后层级发生改变
            catLevel = siblings[i].level;
            //修改其子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      console.info("updateNodes:", this.updateNodes);
    },
    //更新子节点的层级
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    //批量保存方法
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.$notify({
          title: "成功",
          message: "菜单更新成功！！",
          type: "success",
        });
        this.getDataMenu();
        this.expandedKey = this.pCid;
        this.updateNodes = [];
        this.maxLevel = 0;
        this.pCid = [];
      });
    },
    //批量删除的方法
    batchDelete() {
      var data = this.$refs.menuTree.getCheckedNodes();
      console.info("data:", data);
      var catIds = [];
      for (var i = 0; i < data.length; i++) {
        catIds.push(data[i].catId);
      }
      this.$confirm("是否批量删除所选的菜单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            this.$notify({
              title: "成功",
              message: "批量删除成功！",
              type: "success",
            });
            this.getDataMenu();
          });
        })
        .catch(() => {});
    },
  },

  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},

  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getDataMenu();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共 css 类
</style>